package com.ldy.core.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 代理工具
 * 
 * @author lindeyi
 *
 */
@Component
@Configuration
public class ProxyUtil {

	static List<MyProxy> proxys = new ArrayList<>();

	@Value("${ldy-proxys:}")
	private String list;

	@PostConstruct
	public void init() {
		for (String proxyStr : list.split("\\n")) {
			if (!StringUtils.isEmpty(proxyStr) && proxyStr.split(":").length == 4) {
				String[] pp = proxyStr.split(":");
				String proxyIp = pp[0];
				int port = Integer.valueOf(pp[1]);
				String username = pp[2];
				String pwd = pp[3];
				proxys.add(new MyProxy(proxyIp, port, username, pwd));
			}
			if (!StringUtils.isEmpty(proxyStr) && proxyStr.split(":").length == 2) {
				String[] pp = proxyStr.split(":");
				String proxyIp = pp[0];
				int port = Integer.valueOf(pp[1]);
				proxys.add(new MyProxy(proxyIp, port, null, null));
			}
		}
	}

	public static MyProxy getProxy() {
		if (proxys.isEmpty()) {
			return null;
		}
		Random rand = new Random();
		int index = rand.nextInt(proxys.size());
		return proxys.get(index);
	}

	class MyProxy {
		String proxyIp;
		int port;
		String username;
		String pwd;

		MyProxy(String proxyIp, int port, String username, String pwd) {
			this.proxyIp = proxyIp;
			this.port = port;
			this.username = username;
			this.pwd = pwd;
		}

		/**
		 * @return the proxyIp
		 */
		public String getProxyIp() {
			return proxyIp;
		}

		/**
		 * @param proxyIp the proxyIp to set
		 */
		public void setProxyIp(String proxyIp) {
			this.proxyIp = proxyIp;
		}

		/**
		 * @return the port
		 */
		public int getPort() {
			return port;
		}

		/**
		 * @param port the port to set
		 */
		public void setPort(int port) {
			this.port = port;
		}

		/**
		 * @return the username
		 */
		public String getUsername() {
			return username;
		}

		/**
		 * @param username the username to set
		 */
		public void setUsername(String username) {
			this.username = username;
		}

		/**
		 * @return the pwd
		 */
		public String getPwd() {
			return pwd;
		}

		/**
		 * @param pwd the pwd to set
		 */
		public void setPwd(String pwd) {
			this.pwd = pwd;
		}

	}
}
